<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2021/4/24
 * Time: 9:44
 */

namespace App\Http\Controllers\Api\Sesame;


use App\Http\Controllers\Controller;
use App\Patent;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class SyncPatentController extends Controller
{
    public function index(Request $request)
    {
        $data = Patent::query()
            ->where('is_monitor', 1)
            ->when(!$request->has('all'), function ($query) {
                $query->whereHas('dossier', function ($query) {
                    $query->where('status', 3);
                });
            })
            ->when($request->has('agency'), function ($query) {
                $query->whereNull('agency');
            })
            ->whereDate('updated_at', '<', Carbon::now()->subHours(12)->toDateString())
            ->orderBy('updated_at')
            ->pluck('patent_sn', 'patent_sn')->filter(function ($val) {
                if (strlen($val) === 13) {
                    return true;
                }
                $model = Patent::query()->where('patent_sn', $val)->first();
                $model->updated_at = Carbon::now()->addDays(7);
                $model->save();
                return false;
            })->values()->toArray();
        return response()->json(compact('data'));
    }

    public function renew(Request $request)
    {
        $action = $request->get('action');
        $data = $request->get('data') ?: [];
        collect($data)->filter(function ($item) {
            return data_get($item, 'patent_sn');
        })->map(function ($item) use ($action) {
            $patent_sn = data_get($item, 'patent_sn');
            if ($case_status = data_get($item, 'case_status')) {
                $item['legal_status'] = trim($case_status);
            }
            if ($ipc_main = data_get($item, 'ipc')) {
                $item['ipc_main'] = trim($ipc_main);
            }
            $datum = collect($item)->only(['patent_sn', 'apply_date', 'agency', 'legal_status', 'sn_key', 'publication_num', 'publication_date', 'ipc_main', 'agent'])
                ->filter(function ($val) {
                    $val = trim($val);
                    return $val && !in_array($val, ['--', '-']);
                })->all();
            try {
                if (isset($datum['legal_status']) && in_array($datum['legal_status'], ['等待实审提案', '专利权维持'])) {
                    $datum['updated_at'] = Carbon::now()->addDays(7);
                } else {
                    $datum['updated_at'] = Carbon::now();
                }
                if ($action == 'insert') {
                    Patent::query()->updateOrInsert(['patent_sn' => $patent_sn], $datum);
                } else {
                    Patent::query()->where('patent_sn', $patent_sn)->update($datum);
                }

            } catch (\Exception $exception) {
            }
        });
    }

}
